<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace yiike\user\controllers;

use Yii;
use yiike\user\models\Token;
use common\helpers\CommonHelper;
use common\models\LoginForm;
use yiike\user\models\Account;
use yiike\user\models\User;

/**
 * 绑定登录
 * @author Sylar
 */
class NetworksController extends \api\components\UserController {
    
    public $clients = [
        'qq'        => [
            'class'        => 'yiike\user\clients\Qq',
            'clientId'     => '1105319535', //1105319535 ios  1105237062 android
            'name'         => 'qq',
            'clientSecret' => '',
        ],
        'weixin'    => [
            'class'        => 'yiike\wechat\authclient\WechatApp',
            'clientId'     => 'wx6187dd451c922522', //wxdbf2e3a38c77bd38
            'clientSecret' => '2066fc28b70f5b3deb6765a09c3393fd', //9e7fa0078473180a014ea6c90285e2c6
        ],
        'wechat-mp' => [
            'class' => 'yiike\wechat\authclient\WechatMp',
        ],
        'mobile'    => [
            'class' => 'yiike\user\clients\Mobile',
        ]
    ];
    public function actionIndex() {
        $accounes = \dektrium\user\models\Account::findAll(['user_id' => $this->user->id]);
        
        $name = array();
        $data = array(
            'mobile'     => 0,
            'wechat_mp'  => 0,
            'wechat_app' => 0,
            'qq'         => 0,
            'weibo'      => 0,
        );
        if (strlen($this->user->username) == 11 && is_numeric($this->user->username)) {
            $data['mobile'] = 1;
            $name['mobile'] = $this->user->username;
        }        
        foreach ($accounes as $v) {
            $data[$v->provider] = 1;
            $d = json_decode($v->data);
            $name[$v->provider] = isset($d->nickname) ? $d->nickname : '';
        }
        return ['code' => 0, 'data' => $data, 'name' => $name];
    }
    
    public function actionConnect() {        
        $token      = Yii::$app->request->post('token');
        $authclient = Yii::$app->request->post('authclient');
        $params     = Yii::$app->request->post('params');  
        
        if (!$authclient || !$params) {
            return ['code' => 100039];
        }
         
        if ($authclient != 'mobile') {
            $return = $this->connectClient();
        }
        else {
            $return = $this->connectMobile();
        }
        return $return;
    }

    public function actionConfirm() {
        $client  = Yii::$app->request->post('client');
        $user1   = Yii::$app->request->post('user1');
        $user2   = Yii::$app->request->post('user2');
        
        $tokenModel1 = Token::findOne(['code' => $user1['token'], 'type' => Token::TYPE_LOGIN]);
        $tokenModel2 = Token::findOne(['code' => $user2['token'], 'type' => Token::TYPE_LOGIN]);
        
        if ($tokenModel1) {
            $userModel1 = $tokenModel1->user;
        } else {
            return ['code' => 100030, 'message' => 'User1 Token检验失败'];
        }
        
        if ($tokenModel2) {
            $userModel2 = $tokenModel2->user;
        } else {
            return ['code' => 100030, 'message' => 'User2 Token检验失败'];
        }
        
        if ($user1['client'] == $client) {
            if ($user2['client'] == 'mobile') {
                $mobile = $userModel2->username;
                $userModel2->username = 'tmp'.$userModel2->username;
                $userModel2->save();
                
                $userModel1->username = $mobile;
                $userModel1->password = $userModel2->password;
                $userModel1->save();
            }
            else {
                $account = \dektrium\user\models\Account::findAll(['user_id' => $userModel2->id, 'id' => $user2['account_id']]);
                if ($account) {
                    $account->user_id = $userModel1->id;
                    if ($account->save()) {
                        return ['code' => 0];
                    }
                }
            }
        }
        else {
            if ($user1['client'] == 'mobile') {
                $mobile = $userModel1->username;
                $userModel1->username = 'tmp'.$userModel1->username;
                $userModel1->save();
                
                $userModel2->username = $mobile;
                $userModel2->password = $userModel1->password;
                $userModel2->save();
            }
            else {
                $account = \dektrium\user\models\Account::findAll(['user_id' => $userModel1->id, 'id' => $user1['account_id']]);
                if ($account) {
                    $account->user_id = $userModel2->id;
                    if ($account->save()) {
                        return ['code' => 0];
                    }
                }
            }
        }
        return ['code' => 100039, 'message' => '绑定失败'];
    }


    public function connectClient() {
        $authclient = Yii::$app->request->post('authclient');
        $params     = Yii::$app->request->post('params');
 
        try {
            $client  = $this->getClient($authclient, $params);
            if (Account::connectWithUser($client)) {
                return ['code' => 0, 'message' => '绑定成功'];
            }
            else {
                return ['code' => 100039, 'message' => '绑定失败'];
            }
        }
        catch (\yii\base\Exception $e) {
            return ['code' => $e->getCode()];
        }
    }

    public function connectMobile() {
        $params     = Yii::$app->request->post('params');
        $mobile    = $params['mobile'];
        $password  = $params['password'];
        $smscode   = $params['smscode'];
        
        /*
         * 检查手机验证码
         */
        $validator = new \common\models\SmsValidator();
        list($ret, $msg) = $validator->validateCode($mobile, 'network', $smscode);
        if ($ret !== TRUE) {
            return ['code' => $ret, 'message' => $msg];
        }
        
        $tmpUser = User::findOne(['username' => $mobile]);
        if ($tmpUser) {
            $tmpUser->username = md5($mobile);
            $tmpUser->email = null;
            $tmpUser->save(false);
        }
        $user = User::findOne(Yii::$app->user->id);
        $user->scenario = 'settings';
        $user->username = $mobile;
        $user->password = $password;
        $user->email    = $mobile . '@yii.com';
        if ($user->save()) {
            return ['code' => 0, 'message' => '绑定成功', 'user_id' => $user->id,  'username' => $user->username];
        }
        else {
            return ['code' => 100039, 'message' => '绑定失败'];
        }
    }
    /**
     * Runs the action.
     */
    public function getClient($clientId, $params) {
        $this->clients[$clientId] += $params;

        $client = Yii::createObject($this->clients[$clientId]);

        return $client;
    }

}
